package com.sskj.b70.v.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;

import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.b70.R;
import com.sskj.b70.common.App;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.adapter.BaseAdapter;
import com.sskj.b70.common.adapter.ViewHolder;
import com.sskj.b70.common.decoration.DividerLineItemDecoration;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.m.bean.TradePositionListBean;
import com.sskj.b70.m.bean.rxbus.StockLevelUpdate;
import com.sskj.b70.p.fragment.NewTradePositionFragmentPst;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.DisposUtil;
import com.sskj.b70.utils.NumberUtil;
import com.sskj.b70.utils.TipUtil;
import com.sskj.b70.v.activity.TradeActivity;
import com.sskj.b70.v.base.BaseViewPagerFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * <pre>
 *     author : 吕志豪
 *     e-mail : 1030753080@qq.com
 *     time   : 2018/04/09
 *     desc   :杠杆交易 -->持仓订单
 *     version: 1.0
 * </pre>
 */

public class NewTradePositionFragment extends BaseViewPagerFragment<TradeActivity, NewTradePositionFragmentPst> {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private BaseAdapter<TradePositionListBean> adapter;
    private Disposable subscribe;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_trade_position;
    }

    @Override
    public NewTradePositionFragmentPst getPresenter() {
        return new NewTradePositionFragmentPst();
    }

    @Override
    public void initView() {
        refreshLayout.setRefreshHeader(new MaterialHeader(mActivity));
        refreshLayout.setOnRefreshListener(refreshLayout1 -> {
            refreshLayout.finishRefresh();
            mPresenter.loadData();
        });
        startTimer();
    }

    private void startTimer() {
        DisposUtil.close(subscribe);
        subscribe = Flowable.interval(1, TimeUnit.SECONDS)
                .subscribe(i -> mPresenter.loadData());
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (mPresenter != null) {
                startTimer();
            }
        } else {
            DisposUtil.close(subscribe);
        }
    }

    @Override
    public void initData() {
        RxBus.getDefault().register(this);
        mPresenter.loadData();
    }

    @Subscribe(code = Constants.USER_LOGOUT, threadMode = ThreadMode.MAIN)
    public void logout() {
        adapter.setNewData(new ArrayList<>());
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity()).setFirstDraw(false));
        adapter = new BaseAdapter<TradePositionListBean>(R.layout.recy_item_trade_position_h, new ArrayList<>(), recyclerView) {
            @Override
            public void bind(ViewHolder holder, TradePositionListBean data) {
                SpannableString spannableString17 = new SpannableString(data.getStockName());
                RelativeSizeSpan relativeSizeSpan = new RelativeSizeSpan(0.7F);
                ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(
                        Color.parseColor("#AABBCC"));
                StyleSpan styleSpan = new StyleSpan(Typeface.NORMAL);
                spannableString17.setSpan(relativeSizeSpan, data.getPriceUnit().length() - 1, data.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString17.setSpan(foregroundColorSpan, data.getPriceUnit().length() - 1, data.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                spannableString17.setSpan(styleSpan, data.getPriceUnit().length() - 1, data.getStockName().length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                holder.setText(R.id.tv_bz, spannableString17)
                        .setText(R.id.tv_lx, data.getBuyBillType() == 2 ? App.INSTANCE.getString(R.string.strNewTradePositionFragment1) : App.INSTANCE.getString(R.string.strNewTradePositionFragment2))
                        .setText(R.id.tv_time, data.getCreateTime())
                        .setText(R.id.tv_order_num, App.INSTANCE.getString(R.string.strNewTradePositionFragment3) + data.getEntrustNo())
                        .setTextColor(R.id.tv_lx, getResources().getColor(data.getBuyBillType() == 2 ? R.color.market_down : R.color.market_up))
                        .setText(R.id.tv_first_left, NumberUtil.keepNoZoreMax4(data.getBuyPrice()) + "")
                        .setText(R.id.tv_first_right, NumberUtil.keepNoZoreMax4(data.getWinLoseFee()) + "")
                        .setText(R.id.tv_second_left, NumberUtil.keepNoZoreMax4(data.getNewPrice()) + "")
                        .setText(R.id.tv_second_right, NumberUtil.keepNoZoreMax4(data.getBuyMarginFee()) + "")
                        .setText(R.id.tv_third_left, NumberUtil.keepNoZoreMax4(data.getEntrustLot()) + "")
                        .setText(R.id.tv_third_right, NumberUtil.keepNoZoreMax4(data.getBuyDealFee()) + "")
                        .setText(R.id.tv_four_left, NumberUtil.keepNoZoreMax4(data.getStopProfit()) + "")
                        .setText(R.id.tv_four_right, NumberUtil.keepNoZoreMax4(data.getStopLoss()) + "");
                ClickUtil.click(holder.getView(R.id.trade_sale), () -> {
                    TipUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.strNewTradePositionFragment12), () -> {
                        mPresenter.pingcang(data);
                    }).show();
                });
            }
        };
        adapter.setEmtyView();
        recyclerView.setAdapter(adapter);
    }

    public void updateData(List<TradePositionListBean> data) {
        adapter.setNewData(data);
    }

    public void onPingChangSuccess(TradePositionListBean data) {
        adapter.getData().remove(data);
        adapter.notifyDataSetChanged();
        RxBus.getDefault().post(new StockLevelUpdate(""));
    }

    public void update() {
        if (!isHidden()) {
            mPresenter.loadData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DisposUtil.close(subscribe);
    }
}
